/*
 * @Autor: dingxiaolin
 * @Date: 2020-04-14 13:30:31
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2020-05-02 10:25:38
 */
const getRawBody = require('raw-body');
const request = require('request-promise')
const key = process.env['AmapKey']
const search = async (query) => {
    var adcodeQuery = {};
    adcodeQuery.address = query.address;
    adcodeQuery.key = key;
    query.key = key;
    var options = {
        uri: 'https://restapi.amap.com/v3/geocode/geo',
        qs: adcodeQuery,
        json: true
    };
    const result = await request(options)
    console.log('result1', result)
    query.city = result.geocodes[0].adcode;
    var options1 = {
        uri: 'https://restapi.amap.com/v3/weather/weatherInfo',
        qs: query,
        json: true
    };
    const weather = await request(options1)
    console.log('result2', weather)
    return weather
}

// 入口函数
module.exports.handler = function (req, resp, context) {
    getRawBody(req, async (err, body) => {
        if (req.queries.address) {
            try {
                const data = await search(req.queries)
                if (data.status == "1") {//amap请求成功
                    if ((data.lives && data.lives.length > 0) || (data.forecasts && data.forecasts.length > 0)) {//amap请求有结果
                        sendResp(data, true)
                    } else {
                        sendResp("请输入准确的城市地址", false)
                    }
                } else {   //amap请求失败，如key错误
                    sendResp(data, false)
                }
            } catch (err) {
                console.log('err', err)
                sendResp(err, false)
            }
        } else {
            sendResp("请输入城市名称", false)
        }
    });

    // 返回
    sendResp = (data, boolean) => {
        resp.setHeader('content-type', 'application/json');
        try {
            resp.send(JSON.stringify({
                success: boolean,
                data: data
            }));
        }
        catch (err) {
            resp.send(JSON.stringify({
                success: false,
                data: err.message
            }));
        }
    }

}